package com.zjk.toolkit.ratelimiter.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.util.concurrent.RateLimiter;
import com.zjk.toolkit.ratelimiter.annotation.DoRateLimiter;
import com.zjk.toolkit.ratelimiter.constants.Constant;
import com.zjk.toolkit.ratelimiter.service.IRateLimiterService;
import org.aspectj.lang.ProceedingJoinPoint;

import java.lang.reflect.Method;

public class IRateLimiterServiceImpl implements IRateLimiterService {
    @Override
    public Object access(ProceedingJoinPoint joinPoint, Method method, DoRateLimiter doRateLimiter, Object[] args) throws Throwable {
        if (doRateLimiter.limitPerSec()>0) {
            String clazz = joinPoint.getTarget().getClass().getName();
            String methodName = method.getName();
            if (Constant.RATE_LIMITER_CACHE.get(clazz + "." + methodName) == null) {
                Constant.RATE_LIMITER_CACHE.put(clazz + "." + methodName, RateLimiter.create(doRateLimiter.limitPerSec()));
            }
            RateLimiter rateLimiter = Constant.RATE_LIMITER_CACHE.get(clazz + "." + methodName);
            if (rateLimiter.tryAcquire()) {
                return joinPoint.proceed();
            }
            return JSON.parseObject(doRateLimiter.returnJson(),method.getReturnType());

        } else {
            joinPoint.proceed();
        }
        return null;
    }
}
